package vikaa.ui;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;


import vikaa.pushservice.PushService;
import vikaa.tools.HttpUtil;
import vikaa.versonservice.VersonService;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;
import vikaa.wowo.cache.DefaultValueSharePreference;
import vikaa.wowo.cache.UserInfoSharePreference;


public class Welcome extends Activity implements OnClickListener{
	private static final int ACCESS_SUSSESS = 1;
	private static final int ACCESS_FAIL = 0;
	private ImageView login; 
	public static Welcome wl;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
        wl = this;
		if(!isVersonWorked()){
			startService(new Intent(Welcome.this,VersonService.class));
		}
		if(!isPushWorked()){
			PushService.actionStart(getApplicationContext());
		}
        if(!DefaultValueSharePreference.getCheckNew(Welcome.this)){
			new Handler().postDelayed(new Runnable(){
				public void run(){
					Intent intent = new Intent (Welcome.this,Whatsnew.class);			
					startActivity(intent);			
					finish();
				}
			}, 3000);
        }else{
        		new Handler().postDelayed(new Runnable(){
    				public void run(){
    					Intent intent = new Intent();
    		    		intent.setClass(Welcome.this,LookAround.class);
    		    		startActivity(intent);
    		    		finish();
    				}
    			}, 3000);
        }
    }

    private void initview(){
    	login = (ImageView)findViewById(R.id.login);
    	login.setOnClickListener(this);
    }
    public boolean isPushWorked(){
    	ActivityManager myManager=(ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    	ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
    	for(int i = 0 ; i<runningService.size();i++){
    		if(runningService.get(i).service.getClassName().toString().equals("com.vikaa.pushservice.PushService")){
    			return true;
    		}
    	}
    	return false;
    }
    public boolean isVersonWorked(){
    	ActivityManager myManager=(ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    	ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
    	for(int i = 0 ; i<runningService.size();i++){
    		if(runningService.get(i).service.getClassName().toString().equals("com.vikaa.versonservice.VersonService")){
    			return true;
    		}
    	}
    	return false;
    }
    /*public void authroized(){
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(WeiboConstParam.CONSUMER_KEY, WeiboConstParam.CONSUMER_SECRET);	
		weibo.setRedirectUrl(WeiboConstParam.REDIRECT_URL);
		weibo.authorize(Welcome.this, new AuthDialogListener());
		
	}
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.login:
			setContentView(R.layout.loading);
			String token = AuthoSharePreference.getToken(this);
			String oauth_id = AuthoSharePreference.getUid(this);
	    	if (token.equals("") == true){
	    		authroized();
	    	}
	    	Utility.setAuthorization(new Oauth2AccessTokenHeader());
	        AccessToken accessToken = new AccessToken(token, WeiboConstParam.CONSUMER_SECRET);     
	        Weibo.getInstance().setAccessToken(accessToken);
	        new OauthUserThread("sina2", oauth_id, token).start();
	    	break;
		}
	}*/
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case ACCESS_SUSSESS:
				Bundle b = msg.getData();
				String phone_validate = b.getString("phone_validate");
				String uid = b.getString("uid");
				String sessid  = b.getString("phpsessid");	
				//Log.i("afsd", sessid);
				if(phone_validate.equals("1")){
					Intent mywowoIntent = new Intent(Welcome.this,Mywowo.class);
					mywowoIntent.putExtra("uid", uid);
					//save ssid
					AuthoSharePreference.putCookie(Welcome.this, sessid );
					startActivity(mywowoIntent);
					finish();
					}
				else{
					Intent loginIntent = new Intent(Welcome.this,WowoActive.class);
					loginIntent.putExtra("uid", uid);
					startActivity(loginIntent);
					finish();
					}
				break;
			case ACCESS_FAIL:
				if(((String)msg.obj).equals("expired_token") || ((String)msg.obj).equals(getString(R.string.OAUTH_AccessToken_ERROR)) || ((String)msg.obj).equals("invalid_access_token") || ((String)msg.obj).equals("source paramter(appkey) is missing")){
					//authroized();
				}
				else{
					Toast.makeText(Welcome.this, /*getString(R.string.network_not_connected)*/(String)msg.obj, Toast.LENGTH_SHORT).show();
					//setContentView(R.layout.welcome);
					initview();}
				break;
			}
			
		}
		
	};
	class OauthUserThread extends Thread {
		private boolean isrun = true;
		private  String oauth_type;
		private String oauth_id;
		private String oauth_token;
		public OauthUserThread(String oauth_type, String oauth_id,
				String oauth_token) {
			this.oauth_type = oauth_type;
			this.oauth_id = oauth_id;
			this.oauth_token = oauth_token;
		}
		@Override
		public void run() {
			while(isrun){
			Map<String, String> map = new HashMap<String, String>();
			map.put("oauth_type", oauth_type);
			map.put("oauth_token", oauth_token);
			map.put("oauth_id", oauth_id);
			map.put("device_token", Secure.getString(Welcome.this.getContentResolver(), Secure.ANDROID_ID));
			try {
				map.put("client_browser", Welcome.this.getPackageManager().getPackageInfo("com.vikaa.wowo", 0).versionName);
				map.put("client_screen", getWindowManager().getDefaultDisplay().getWidth() + "x" + getWindowManager().getDefaultDisplay().getHeight());
				map.put("client_os", android.os.Build.VERSION.RELEASE);
				map.put("client_type", android.os.Build.MODEL);
			} catch (NameNotFoundException e1) {
				e1.printStackTrace();
			}
			String url = HttpUtil.BASE_URL + "user/oauthlogin";
			try {
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				String result = jsonObj.getString("result");
				if(result.equals("1")){
					isrun = false;
					String phone_validate = jsonObj.getJSONObject("info").getString("phone_validate");
					String uid = jsonObj.getJSONObject("info").getString("uid");
					String phpSESSID = null;
					if(phone_validate.equals("1")){
					phpSESSID = jsonObj.getJSONObject("info").getString("PHPSESSID");}
					UserInfoSharePreference.putNickname(Welcome.this, jsonObj.getJSONObject("info").getString("nickname"));
					UserInfoSharePreference.putUid(Welcome.this, uid);
					UserInfoSharePreference.putAvater(Welcome.this, jsonObj.getJSONObject("info").getString("avatar"));
					UserInfoSharePreference.putEmail(Welcome.this, jsonObj.getJSONObject("info").getString("email"));
					UserInfoSharePreference.putPhone(Welcome.this, jsonObj.getJSONObject("info").getString("phone"));
					UserInfoSharePreference.putCrash(Welcome.this, "0");
					Message msg = mhandler.obtainMessage(ACCESS_SUSSESS);
					Bundle b = msg.getData();
					b.putString("phone_validate", phone_validate);
					b.putString("phpsessid", phpSESSID);
					b.putString("uid", uid);
					mhandler.sendMessage(msg);
				}else if(result.equals("0")){
					isrun = false;
					String error = jsonObj.getString("msg");
					Message msg = mhandler.obtainMessage(ACCESS_FAIL);
					msg.obj = error;
					mhandler.sendMessage(msg);
				}
				else{
					isrun = false;
					String error = jsonObj.getJSONObject("info").getString("error");
					Message msg = mhandler.obtainMessage(ACCESS_FAIL);
					msg.obj = error;
					mhandler.sendMessage(msg);
				}
			}  catch (Exception e) {
				isrun = false;
				e.printStackTrace();
				}
			}
		}
		
	}
	/*class AuthDialogListener implements WeiboDialogListener {

		public void onComplete(Bundle values) {
			String oauth_token  = values.getString("access_token");	
			AuthoSharePreference.putToken(Welcome.this, oauth_token );
			
			String tokenString = AuthoSharePreference.getToken(Welcome.this);				
			AccessToken accessToken = new AccessToken(tokenString, WeiboConstParam.CONSUMER_SECRET);		
		    Weibo weibo = Weibo.getInstance();	
		    weibo.setAccessToken(accessToken);
		    
		    String expires_in = values.getString("expires_in");
		    AuthoSharePreference.putExpires(Welcome.this, expires_in);
		   
		    String remind_in = values.getString("remind_in");
		    AuthoSharePreference.putRemind(Welcome.this, remind_in);		    
		    
		    String oauth_id  = values.getString("uid");
		    AuthoSharePreference.putUid(Welcome.this, oauth_id );
		    
		    String oauth_type = "sina2";
		    
		    new OauthUserThread(oauth_type, oauth_id, oauth_token).start();
			//goPlayActivity();
		}
		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}
		public void onCancel() {
			
		}
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}*/
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
}
